import socket
import threading

class ESP32TCPHandler:
    def __init__(self, host='0.0.0.0', port=8888):
        """
        初始化TCP服务器
        :param host: 监听地址（默认所有可用接口）
        :param port: 监听端口（默认8888）
        """
        self.host = host
        self.port = port
        self.server_socket = None
        self.client_socket = None
        self.client_address = None
        self.running = False
        self.callback = None  # 接收数据回调函数

    def start_server(self):
        """启动TCP服务器"""
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.server_socket.bind((self.host, self.port))
        self.server_socket.listen(1)
        self.running = True
        print(f"Server started on {self.host}:{self.port}")

        # 启动接受客户端连接的线程
        accept_thread = threading.Thread(target=self._accept_clients)
        accept_thread.daemon = True
        accept_thread.start()

    def _accept_clients(self):
        """接受客户端连接（内部方法）"""
        while self.running:
            try:
                self.client_socket, self.client_address = self.server_socket.accept()
                print(f"Connected by {self.client_address}")
                
                # 启动接收数据的线程
                receive_thread = threading.Thread(target=self._receive_data)
                receive_thread.daemon = True
                receive_thread.start()
            except Exception as e:
                if self.running:
                    print(f"Accept error: {str(e)}")

    def _receive_data(self):
        """接收数据循环（内部方法）"""
        while self.running and self.client_socket:
            try:
                data = self.client_socket.recv(1024)
                if data:
                    if self.callback:
                        self.callback(data)  # 触发回调函数
                    print(f"Received: {data.decode().strip()}")
                else:
                    self._disconnect_client()
            except Exception as e:
                print(f"Receive error: {str(e)}")
                self._disconnect_client()

    def send_data(self, data):
        """发送数据到客户端"""
        if self.client_socket:
            try:
                if isinstance(data, str):
                    data = data.encode()
                self.client_socket.sendall(data)
                return True
            except Exception as e:
                print(f"Send error: {str(e)}")
                self._disconnect_client()
                return False
        return False

    def _disconnect_client(self):
        """断开客户端连接（内部方法）"""
        if self.client_socket:
            try:
                self.client_socket.close()
            except:
                pass
            self.client_socket = None
            print("Client disconnected")

    def stop_server(self):
        """停止服务器"""
        self.running = False
        self._disconnect_client()
        if self.server_socket:
            try:
                self.server_socket.close()
            except:
                pass
            self.server_socket = None
        print("Server stopped")

    def set_callback(self, callback_func):
        """设置接收数据回调函数"""
        self.callback = callback_func

# # 测试用例
# if __name__ == "__main__":
#     def data_received(data):
#         print(f"[Callback] Received: {data.decode()}")

#     server = ESP32TCPHandler(port=8888)
#     server.set_callback(data_received)
#     server.start_server()

#     try:
#         while True:
#             # 示例：发送数据到ESP32
#             msg = input("Enter message to send (q to quit): ")
#             if msg.lower() == 'q':
#                 break
#             server.send_data(msg + "\n")
#     finally:
#         server.stop_server()
